package com.xinhe.web.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Slf4j
 public class HttpClientUtil {

   private static final HttpClient client = (HttpClient)createSSLInsecureClient();
   private static final RequestConfig config = RequestConfig.custom()
     .setConnectTimeout(30000)
     .setConnectionRequestTimeout(30000)
     .setSocketTimeout(30000)
     .build();







   public static CloseableHttpClient createSSLInsecureClient() {
     try {
       SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((chain, authType) -> true).build();
       SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, (hostname, session) -> true);

       return HttpClients.custom().setSSLSocketFactory((LayeredConnectionSocketFactory)sslsf).build();
     } catch (GeneralSecurityException var2) {
       throw new RuntimeException(var2);
     }
   }

   public static HttpClient getClient() {
     return client;
   }







   public static HttpEntity requestGet(String url, Map<String, Object> params) {
     String uri = url;
     if (!CollectionUtils.isEmpty(params)) {
       StringBuilder param = new StringBuilder("?");
       Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
       while (iterator.hasNext()) {
         Map.Entry<String, Object> next = iterator.next();
         param.append(next.getKey()).append("=").append(next.getValue());
         if (iterator.hasNext()) {
           param.append("&");
         }
       }
       uri = uri + param.toString();
     }
     HttpGet get = new HttpGet(uri);
     get.setConfig(config);
     HttpResponse execute = null;
     try {
       execute = client.execute((HttpUriRequest)get);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求GET异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       return null;
     }
     return execute.getEntity();
   }

   public static JSONObject requestGet(String url, Map<String, Object> params, Map<String, Object> headers) {
     String uri = url;
     if (!CollectionUtils.isEmpty(params)) {
       StringBuilder param = new StringBuilder("?");
       Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
       while (iterator.hasNext()) {
         Map.Entry<String, Object> next = iterator.next();
         param.append(next.getKey()).append("=").append(next.getValue());
         if (iterator.hasNext()) {
           param.append("&");
         }
       }
       uri = uri + param.toString();
     }
     HttpGet get = new HttpGet(uri);
     get.setConfig(config);

     for (Map.Entry<String, Object> next : headers.entrySet()) {
       get.addHeader(next.getKey(), next.getValue().toString());
     }

     HttpResponse execute = null;
     try {
       execute = client.execute((HttpUriRequest)get);
       HttpEntity entity = execute.getEntity();
       String respJson = EntityUtils.toString(entity);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return JSONObject.parseObject(respJson);
       }
       log.error("远程请求GET异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), respJson });
     } catch (IOException e) {
       return null;
     }
     return null;
   }
   public static HttpEntity requestGet(String url) {
     HttpGet get = new HttpGet(url);
     get.setConfig(config);
     HttpResponse execute = null;
     try {
       execute = client.execute((HttpUriRequest)get);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求GET异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       return null;
     }
     return execute.getEntity();
   }
   public static HttpEntity requestPost(String url, Map<String, String> params) {
     List<NameValuePair> list = new ArrayList<>();
     for (Map.Entry<String, String> next : params.entrySet()) {
       list.add(new BasicNameValuePair(next.getKey(), next.getValue()));
     }
     HttpPost post = new HttpPost(url);
     post.setConfig(config);
     HttpResponse execute = null;
     try {
       post.setEntity((HttpEntity)new UrlEncodedFormEntity(list, "utf-8"));
       execute = client.execute((HttpUriRequest)post);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求POST异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       log.error("请求异常：{}", e.getMessage());
       return null;
     }
     return execute.getEntity();
   }

   public static HttpEntity requestJsonPut(String url, Map<String, Object> params, Map<String, String> headers) {
     JSONObject jsonObject = new JSONObject(params);
     HttpPut put = new HttpPut(url);
     for (Map.Entry<String, String> next : headers.entrySet()) {
       put.addHeader(next.getKey(), next.getValue());
     }
     put.setConfig(config);
     HttpResponse execute = null;
     try {
       put.setEntity((HttpEntity)new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON));
       execute = client.execute((HttpUriRequest)put);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求POST异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       return null;
     }
     return execute.getEntity();
   }
   public static JSONObject requestJsonPost(String url, Map<String, Object> params, Map<String, String> headers) {
     JSONObject jsonObject = new JSONObject(params);
     HttpPost post = new HttpPost(url);
     for (Map.Entry<String, String> next : headers.entrySet()) {
       post.addHeader(next.getKey(), next.getValue());
     }
     post.setConfig(config);
     HttpResponse execute = null;
     JSONObject json = null;
     try {
       post.setEntity((HttpEntity)new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON));
       execute = client.execute((HttpUriRequest)post);
       String s = EntityUtils.toString(execute.getEntity());
       json = JSONObject.parseObject(s);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return json;
       }
       log.info("远程请求POST异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), json.toJSONString() });
     } catch (IOException e) {
       log.error("postJson请求错误：{}", e.getMessage());
       return null;
     }
     return json;
   }

   public static HttpEntity requestJsonDelete(String url, Map<String, Object> params, Map<String, String> headers) {
     JSONObject jsonObject = new JSONObject(params);
     HttpDeleteBody delete = new HttpDeleteBody(url);
     for (Map.Entry<String, String> next : headers.entrySet()) {
       delete.addHeader(next.getKey(), next.getValue());
     }
     delete.setConfig(config);
     HttpResponse execute = null;
     try {
       delete.setEntity((HttpEntity)new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON));
       execute = client.execute((HttpUriRequest)delete);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求POST异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       return null;
     }
     return execute.getEntity();
   }
   public static HttpEntity requestPost(String url, Map<String, String> params, Map<String, String> headers) {
     List<NameValuePair> list = new ArrayList<>();
     for (Map.Entry<String, String> next : params.entrySet()) {
       list.add(new BasicNameValuePair(next.getKey(), next.getValue()));
     }

     HttpPost post = new HttpPost(url);
     for (Map.Entry<String, String> next : headers.entrySet()) {
       post.addHeader(next.getKey(), next.getValue());
     }
     post.setConfig(config);
     HttpResponse execute = null;
     try {
       post.setEntity((HttpEntity)new UrlEncodedFormEntity(list, "utf-8"));
       execute = client.execute((HttpUriRequest)post);
       if (execute.getStatusLine().getStatusCode() == 200) {
         return execute.getEntity();
       }
       log.error("远程请求POST异常，url：{}，code：{},error: {}", new Object[] { url, Integer.valueOf(execute.getStatusLine().getStatusCode()), EntityUtils.toString(execute.getEntity()) });
     } catch (IOException e) {
       return null;
     }
     return execute.getEntity();
   }
 }
